package com.wuyou.dataStructure.tree;

import com.sun.xml.internal.org.jvnet.fastinfoset.EncodingAlgorithmIndexes;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树最大深度
 */
public class MaxDepth {

    public static void main(String[] args) {
        MaxDepth main = new MaxDepth();
        TreeNode root = new TreeNode(1);
        TreeNode root2 = new TreeNode(2);
        TreeNode root3 = new TreeNode(3);
        TreeNode root4 = new TreeNode(4);
        TreeNode root5 = new TreeNode(5);
        root.left=root2;
        root.right=root3;
        root.left.left=root4;
        root.right.right=root5;
        System.out.println(main.maxDepth(root));
        System.out.println(main.sol_2(root));
        System.out.println(main.sol_3(root));
    }
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

    /**
     * BFS Breath First Search
     * 二叉树总节点数量
     * @param root
     * @return
     */
    public int sol_3(TreeNode root){
        if (root == null) {
            return 0;
        }
        List<List<Integer>> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            // 每层的节点数量
            int levelNum = queue.size();
            List<Integer> tempList = new ArrayList<>();
            for(int i=0;i<levelNum;i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            ans.add(tempList);
        }
        return ans.size();
    }

    /**
     * BFS Breath First Search
     * 二叉树总节点数量
     * @param root
     * @return
     */
    public int sol_2(TreeNode root){
        if (root == null) {
            return 0;
        }
        int ans = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            ans++;
            TreeNode node = queue.poll();
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        return ans;
    }
}
